<?php
/*
Author: SwiftShadow-FPL
Time: 2016/11/24
Objective: To deal with Concurrenct Transaction 
Method: To use _redisKeyInterFace to build the new Function
*/
class SS_model extends CI_Model
{
	protected $redis;
	public function __construct()
	{
		$this->load->database();
		$this->redis = new Redis();
		$this->redis->pconnect('127.0.0.1','6379');
		$this->redis->auth(REDIS_PASS);
	}

	public function _getLock($key_id)
	{
		$timestamp = time();
		$flag = 0;
		while($flag != 1)
		{
			$time = $this->redis->get($key_id);
			if(empty($time))
			{
				$this->redis->setnx($key_id,$timestamp);
				$flag = 1;
			}
			else
			{
				if(($timestamp-$time) > 10)
				{
					$this->redis->set($key_id,$timestamp);
					$flag = 1;
				}
				else
				{
					return array("code"=>"201","content"=>"busy");
					usleep(1000);
				}
			}
		}
		return array("code"=>"200","content"=>"success");
	}

	public function _releaseLock($key_id)
	{
		$time = $this->redis->get($key_id);
		$this->redis->del($key_id);
		return $time;
	}
	
	public function _redisKeyInterFace($function,$key_id,$data)
	{
		if($this->_getLock($key_id)['code'] == '200')
		{
			$result = $this->$function($data);
			$this->_releaseLock($key_id);
			return $result;
		}
		return array("code"=>"201","content"=>"busy");
	}

	public function mail_to($data)
	{
		mail($data['to'],$data['title'],$data['content']);
	}
}